#include "snapshotsettingdialog.h"
#include "ui_snapshotsettingdialog.h"

SnapShotSettingDialog::SnapShotSettingDialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::SnapShotSettingDialog)
{
    ui->setupUi(this);
    initUI();
}

SnapShotSettingDialog::~SnapShotSettingDialog()
{
    delete ui;
}

void SnapShotSettingDialog::initUI()
{
    // 设置文件名 LineEdit 的验证器（只允许字母、数字、下划线）
    QRegularExpression fileNameRegex("^[a-zA-Z0-9_]+$"); // 正则表达式
    QRegularExpressionValidator *fileNameValidator = new QRegularExpressionValidator(fileNameRegex, this);
    ui->fileNameLe->setValidator(fileNameValidator);

    // 设置分辨率 LineEdit 的验证器（只允许数字）
    QRegularExpression resRegex("^[0-9]+$"); // 只允许数字
    QRegularExpressionValidator *resValidator = new QRegularExpressionValidator(resRegex, this);
    ui->resWidthLe->setValidator(resValidator);
    ui->resHeightLe->setValidator(resValidator);

    ui->fileNameLe->setText("temp");
    ui->resWidthLe->setText("1024");
    ui->resHeightLe->setText("1024");
    ui->fileFormationCmb->addItem("PNG", "png");
    ui->fileFormationCmb->addItem("JPG", "jpg");
    ui->fileFormationCmb->addItem("TIFF", "tiff");
    // 暂不支持
    // ui->fileFormationCmb->addItem("BMP", "bmp");
    ui->fileFormationCmb->setCurrentIndex(0);
}

QString SnapShotSettingDialog::getFileName() const
{
    QString fileName = ui->fileNameLe->text();
    if (fileName.isEmpty()) {
        return "";
    }
    return fileName;
}

QString SnapShotSettingDialog::getFileFormat() const
{
    auto strFormation = ui->fileFormationCmb->currentText().toStdString();
    return QString::fromStdString(getStringFromFormat(getFormatFromString(strFormation).value()));
}

qsizetype SnapShotSettingDialog::getResWidth() const
{
    bool ok;
    qsizetype width = ui->resWidthLe->text().toLongLong(&ok);
    if (!ok || width <= 0) {
        return -1; // 或返回默认值
    }
    return width;
}

qsizetype SnapShotSettingDialog::getResHeight() const
{
    bool ok;
    qsizetype height = ui->resHeightLe->text().toLongLong(&ok);
    if (!ok || height <= 0) {
        return -1; // 或返回默认值
    }
    return height;
}

std::vector<std::string> SnapShotSettingDialog::getSupportedFormats() const
{
    return {"PNG", "JPG", "TIFF"};
}

std::optional<ImageFormat> SnapShotSettingDialog::getFormatFromString(const std::string &formatStr) const
{
    auto it = stringToFormat.find(formatStr);
    if (it != stringToFormat.end()) {
        return it->second;
    }
    return std::nullopt;
}

std::string SnapShotSettingDialog::getStringFromFormat(ImageFormat format) const
{
    return formatToString.at(format);
}
